package heven.holt.wan.android.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import heven.holt.library.base.BaseFragment
import heven.holt.library.loading.extensions.setLoadingStateCommonDecorHeader
import heven.holt.library.adapter.CommonViewPagerAdapter
import heven.holt.wan.android.databinding.FragmentSystemBinding
import heven.holt.wan.android.loading.delegate.CommonTitleDelegate
import heven.holt.wan.android.viewmodel.NavigationViewModel

@AndroidEntryPoint
class SystemFragment : BaseFragment<FragmentSystemBinding>() {

    private val args: SystemFragmentArgs by navArgs()

    private val navigationViewModel: NavigationViewModel by viewModels()

    private val commonTitleDelegate = CommonTitleDelegate()

    override fun bindViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): FragmentSystemBinding = FragmentSystemBinding.inflate(inflater, container, false)

    override fun createDecorationView(): View {
        val loadingStateView =
            binding.root.setLoadingStateCommonDecorHeader(commonTitleDelegate)
        return loadingStateView.decorView
    }

    override fun initView() {
    }

    override fun initData() {
        navigationViewModel.navigationProjectModelLiveData.observe(viewLifecycleOwner) { projectModel ->
            projectModel.name?.let { commonTitleDelegate.setTitle(it) }

            val fragments = mutableListOf<Fragment>()
            projectModel.children?.forEach {
                fragments.add(SystemArticleFragment.newInstance(it.id ?: 0))
            }
            binding.viewPager.adapter = CommonViewPagerAdapter(this, fragments)
            TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
                tab.text = projectModel.children!![position].name
            }.attach()
            val position = navigationViewModel.requestPositionByProjectTree(projectModel)
                ?: return@observe
            binding.viewPager.setCurrentItem(position, false)
            binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
                override fun onPageSelected(position: Int) {
                    val cid = projectModel?.children?.get(position)?.id ?: return
                    navigationViewModel.setCurrentCid(cid)
                }
            })
        }

        if (navigationViewModel.navigationProjectModelLiveData.value == null) {
            navigationViewModel.setCurrentCid(args.cid)
            navigationViewModel.requestProjectModelByCid()
        }
    }
}